package com.kucun.util;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.sdlc.com.database.BaseDaoInterface;
import org.sdlc.com.database.bean.CglibDynaBean;
import org.sdlc.com.database.impl.MysqlBaseDaoImpl;

public class TreeNodeTest {
	@Test
	public void loadTree() throws Exception{
	System.out.println(recursiveTree((long) 1));
	}
	public static void main(String[] args) {
		System.out.println(recursiveTree((long) 1));
	}
	/**
	* 递归算法解析成树形结构
	*
	* @param long1
	* @return
	* @author jiqinlin
	*/
	public static TreeNode recursiveTree(Long long1) {
		BaseDaoInterface basedao=MysqlBaseDaoImpl.getInstance();
		List<CglibDynaBean> lists=null;
		lists= basedao.getListCglib("select * from repertory ");
	//根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
	CglibDynaBean node = (CglibDynaBean) basedao.getSingleCglib("select * from repertory where Id="+long1, null);
			TreeNode t1=new TreeNode();
	t1.setCname((String) node.getValue("titles"));
	t1.setCid( (Long) node.getValue("id"));
	t1.setPid((Integer)node.getValue("parentid"));
	//查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
	List childTreeNodes = basedao.getListCglib( "select * from repertory where parentId="+long1,null);
	List<TreeNode> list1 = new ArrayList<TreeNode>();
	for (Object object : childTreeNodes) {
		TreeNode t2=new TreeNode();
		t2.setCname((String) node.getValue("titles"));
		t2.setCid((Long) node.getValue("id"));
		t2.setPid((Integer)node.getValue("parentid"));
		t2.setNodes((List) object);
		list1.add(t2);
	}
	//遍历子节点
	for(TreeNode child : list1){
		TreeNode n = recursiveTree(child.getCid()); //递归
		t1.getNodes().add(n);
	}
	 
	return t1;
	}
}
